"""
Description: 路由管理
Author: 月间
Date: 2024-10-15 23:34:41
LastEditTime: 2025-03-22 19:08:52
LastEditors: 月间
"""

from typing import Any

from fastapi import APIRouter, Depends
from fastapi_utils.cbv import cbv
from sqlalchemy import and_
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.sql.expression import true

from authx.dependencies.auth import RequireLogin
from src.core.base_controller import BaseController
from src.core.response import ResponseSchema
from src.db.db_database import alchemy
from src.models import SysMenu
from src.services.menu_service import MenuService

router = APIRouter()


# ===============================
# 路由管理
# ===============================
@cbv(router)
class RouterController(BaseController):
    """
    路由管理
    """

    db: AsyncSession = Depends(alchemy.provide_session())
    menu_service: MenuService = Depends(alchemy.provide_service(MenuService))

    # 获取静态路由
    @router.get(
        "/getConstantRoutes",
        summary="静态路由",
        response_model=ResponseSchema,
    )
    async def get_static_route(self):
        res = await self.menu_service.list(
            and_(SysMenu.constant == true(), SysMenu.status == "1")
        )
        route = []
        for menu_obj in res:
            route_data = {
                "name": menu_obj.route_name,
                "path": menu_obj.route_path,
                "component": menu_obj.component,
                "meta": {
                    "title": menu_obj.menu_name,
                    "i18nKey": menu_obj.i18n_key,
                    "constant": menu_obj.constant,
                    "hideInMenu": menu_obj.hide_in_menu,
                },
            }

            if menu_obj.props:
                route_data["props"] = True

            route.append(route_data)
        return self.success(data=route)

    @router.get("/getUserRoutes", summary="动态路由", response_model=ResponseSchema)
    async def get_dynamic_route(self, login_id: Any = Depends(RequireLogin())):
        user = await self.get_current_user(self.db, login_id)
        routes = await self.menu_service.get_user_menu(user)
        index = "home"
        if not user.roles:
            roles = user.roles
            index = roles[0].home_key
        return self.success(data={"home": index, "routes": routes})
